from django.db.models import Q
from rest_framework import viewsets
from ERP_system.utils.multiple_destory import MultipleDestoryMixin,MultipleOpenMixin
from ERP_system.utils.pagination import GlobalPagination
from rest_framework import mixins,viewsets
from purchase_info.models import  PurchaseModel,PurchaseItemModel
from purchase_info.serializer.purchase_serializer import PurchaseSerializer,PurchaseGetSerializer


class PurchaseView(viewsets.ModelViewSet,MultipleDestoryMixin):

    queryset = PurchaseModel.objects.all()
    serializer_class = PurchaseSerializer
    pagination_class = GlobalPagination

    def get_serializer_class(self):
        if self.action == 'retrieve':
            return PurchaseGetSerializer
        return PurchaseSerializer

    def get_queryset(self):
        print(dir(PurchaseModel))
        if self.action == 'find':  # 过滤查询
            # 获取请求参数(在json中)：
            number_code = self.request.data.get('number_code', None)
            keyword = self.request.data.get('keyword', None)
            supplier = self.request.data.get('supplier', 0)
            operator_user = self.request.data.get('operator_user', 0)
            status = self.request.data.get('status', None)
            query = Q()
            if keyword:
                child_query = Q()
                child_query.add(Q(item_list__name__contains=keyword), 'OR')
                child_query.add(Q(item_list__specification=keyword), 'OR')
                query.add(child_query, 'AND')
            if supplier:
                query.add(Q(supplier__id=supplier), 'AND')
            if number_code:
                query.add(Q(number_code__contains=number_code), 'AND')
            if operator_user:
                query.add(Q(operator_user__id=operator_user), 'AND')
            if status:
                query.add(Q(status=status), 'AND')

            return PurchaseModel.objects.filter(query).distinct().all()
        else:
            return PurchaseModel.objects.all()




